<?php

namespace App\Http\Controllers\Setting;

use App\Http\Controllers\Controller;
use App\Http\Requests\Setting\RoleIndexRequest;
use App\Http\Requests\Setting\RoleStoreRequest;
use App\Models\Role;
use App\Models\RoleRelMenu;

class RoleController extends Controller
{
    public function index(RoleIndexRequest $request): array
    {
        $params = $request->validated();
        $page = $params['page'] ?? 1;
        $pageSize = $params['pageSize'] ?? 10;

        $model = Role::query()->when($params['name'] ?? false, fn($query, $name) => $query->where('name', 'like', $name . '%'));
        $total = (clone $model)->count();
        $list = $model->with('menus')->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->orderBy('id', 'desc')
            ->get()
            ->toArray();
        return $this->success(compact('list', 'total'));
    }

    public function options():array
    {
        return $this->success(Role::query()->get(['id', 'name'])->toArray());
    }

    public function store(RoleStoreRequest $request): array
    {
        $params = $request->validated();
        $menus = $params['relMenus'] ?? [];
        unset($params['relMenus']);
        $id = Role::query()->insertGetId($params);
        RoleRelMenu::query()->insert(array_map(fn($v) => ['role_id' => $id, 'menu_id' => $v], $menus));
        return $this->success();
    }

    public function detail(int $id): array
    {
        $data = Role::query()->find($id)->toArray();
        return $this->success($data);
    }

    public function update(int $id, RoleStoreRequest $request): array
    {
        $params = $request->validated();
        $menus = $params['relMenus'] ?? [];
        unset($params['relMenus']);
        Role::query()->where('id', $id)->update($params);
        RoleRelMenu::query()->where('role_id', $id)->delete();
        RoleRelMenu::query()->insert(array_map(fn($v) => ['role_id' => $id, 'menu_id' => $v], $menus));
        return $this->success();
    }
}
